package org.apache.ibatis.ibator.pluginpo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.ibator.api.ShellCallback;
import org.apache.ibatis.ibator.config.MergeConstants;
import org.apache.ibatis.ibator.exception.ShellException;
import org.apache.ibatis.ibator.internal.util.messages.Messages;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

public class GenRule {

	static String serviceNameTemp = "#base#ServiceImpl";
	static String listTemp = "#base#s";
	static String base = "#base#";
	static String serviceInterFaceNameTemp = "I#base#Service";
	static String daoNameTemp = "#base#DAO";
	static String daoInterFaceNameTemp = "I#base#DAO";
	static String aliasExampleName = "#base#Example";
	static String actionName = "#base#MngAction";
	static String createPage = "#base#Create.ftl";
	static String updatePage = "#base#Detail.ftl";
	static String getPage = "#base#Detail.ftl";
	static String listPage = "#base#List.ftl";

	/**
	 * ��ݻ�alias��� �������
	 * 
	 * @param baseAlias
	 * @return
	 */

	public static String genNameByType(String baseAlias, String type) {

		if (isBlank(baseAlias) || isBlank(type))
			return baseAlias;
		else if (type.equalsIgnoreCase("service"))
			return serviceNameTemp.replaceFirst("#base#", baseAlias);
		else if (type.equalsIgnoreCase("base"))
			return serviceNameTemp.replaceFirst("#base#", baseAlias);
		else if (type.equalsIgnoreCase("list"))
			return listTemp.replaceFirst("#base#", baseAlias);
		else if (type.equalsIgnoreCase("serviceI"))
			return serviceInterFaceNameTemp.replaceFirst("#base#", baseAlias);
		else if (type.equalsIgnoreCase("dao"))
			return daoNameTemp.replaceFirst("#base#", baseAlias);
		else if (type.equalsIgnoreCase("daoI"))
			return daoInterFaceNameTemp.replaceFirst("#base#", baseAlias);
		else if (type.equalsIgnoreCase("example"))
			return aliasExampleName.replaceFirst("#base#", baseAlias);
		else if (type.equalsIgnoreCase("action"))
			return actionName.replaceFirst("#base#", baseAlias);
		else if (type.equalsIgnoreCase("createPage"))
			return createPage.replaceFirst("#base#", baseAlias);
		else if (type.equalsIgnoreCase("updatePage"))
			return updatePage.replaceFirst("#base#", baseAlias);
		else if (type.equalsIgnoreCase("getPage"))
			return getPage.replaceFirst("#base#", baseAlias);
		else if (type.equalsIgnoreCase("listPage"))
			return listPage.replaceFirst("#base#", baseAlias);
		else
			return baseAlias;

	}

	public static String capFirst(String str) {
		if (str != null && str.length() > 0) {
			return str.substring(0, 1).toUpperCase() + str.substring(1, str.length());
		} else
			return str;

	}

	public static String uncapFirst(String str) {
		if (str != null && str.length() > 0) {
			return str.substring(0, 1).toLowerCase() + str.substring(1, str.length());
		} else
			return str;
	}

	public static boolean isBlank(String str) {
		if (str == null || str.replaceAll(" ", "").equals(""))
			return true;
		else
			return false;
	}

	public static void main(String arg[]) {
		System.out.println((int)Math.pow(2,5));

	}

	public void genFile(ShellCallback shellCallback, Map rootMap, String pathPrefix, String targetSrc,
			String packageName, String outPutName, String templetName, List<String> warnings,Boolean overwrite) throws Exception {
		Configuration cfg = new Configuration();
//		cfg.setDirectoryForTemplateLoading(new File(directForTemp));
		cfg.setClassForTemplateLoading(GenRule.class, "/resources"+pathPrefix);

		cfg.setObjectWrapper(new DefaultObjectWrapper());
		try {
			File directory = shellCallback.getDirectory(targetSrc, packageName, warnings);
			File targetFile = new File(directory, outPutName);
			
			if (targetFile.exists()) {
                if(!overwrite){
                	 targetFile = getUniqueFileName(directory, outPutName);
                   }
             
            	
            }
			
			Writer out = new OutputStreamWriter(new FileOutputStream(targetFile));
			Template temp = cfg.getTemplate(templetName);
			temp.process(rootMap, out);
			out.flush();
		} catch (ShellException e) {
			warnings.add(e.getMessage());
		}

	}
	
	 private File getUniqueFileName(File directory, String fileName) {
	        File answer = null;
	        
	        // try up to 1000 times to generate a unique file name
	        StringBuffer sb = new StringBuffer();
	        for (int i = 1; i < 1000; i++) {
	            sb.setLength(0);
	            sb.append(fileName);
	            sb.append('.');
	            sb.append(i);
	            
	            File testFile = new File(directory, sb.toString());
	            if (!testFile.exists()) {
	                answer = testFile;
	                break;
	            }
	        }
	        
	        if (answer == null) {
	            throw new RuntimeException(Messages.getString("RuntimeError.3", directory.getAbsolutePath())); //$NON-NLS-1$
	        }
	        
	        return answer;
	    }
	 
	 public  long getMax(int length){
		return  (int)Math.pow(10,length+1)-1; 
	 }
	 
	

}
